/*
 * @Author: 天稻 2283341909@qq.com
 * @Date: 2023-02-15 23:59:24
 * @LastEditors: 天稻 2283341909@qq.com
 * @LastEditTime: 2023-04-17 23:50:18
 * @FilePath: \node-project\app.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const express = require('express')
const path = require('path')
const musicLogin = require('./routers/music/login')
const backManage = require('./routers/manage/login')
const routerIndex = require('./routers/index')
const session = require('express-session')
const cookieParser = require('cookie-parser')

const app = express()

app.use(
  session({
    secret: 'keyboard cat',
    cookie: { maxAge: 1000 * 60 * 60 * 24 },
    resave: true,
    saveUninitialized: true
  })
)
app.set('trust proxy', 1)

app.use(cookieParser())
app.engine('html', require('express-art-template'))
app.use('/public', express.static('./public'))
app.use('/upload', express.static('./upload'))
app.use('/node_modules', express.static('../node_modules'))

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.use(routerIndex)
app.use(musicLogin)
app.use(backManage)

const waringcode = [
  '99998', // 常见问题
  '99996', // 客户端未登录
  '99997' // 后管未登录，客户端未登录不报错
]
// next([message,code])
app.use(function (err, request, response, next) {
  // 格式：[message,code]
  console.log(err)
  if (!waringcode.includes(`${err[1]}`)) return next(err)
  if (err[1] == waringcode[1]) delete request.session.userNo
  response.json({
    code: `${err[1]}`,
    msg: err[0]
  })
})
// next([message]) or next(message)
app.use(function (err, request, response, next) {
  if(!Array.isArray(err)) err=[err]
  response.status(500).json({
    code: '99999',
    meg: `服务器爆炸,${err[0]}`
  })
})
//next()
app.use(function (req, res, next) {
  res.status(500).json({
    code: '99999',
    meg: `服务器爆炸,芭比Q了`
  })
})

app.listen(2023, function () {
  console.log('2023端口已开启.....')
})
